# 全局夹具
import base64
import pytest
import yaml
import os
import ddddocr
import requests
import requests
# 读取环境变量（默认test）
base_url = ''
@pytest.fixture(scope='session', autouse=True)
def getenv():
    env = os.getenv("APP_ENV", "test").lower()#若未配置，环境变量变为test
    with open(f"config/{env}.yaml") as f:
        config = yaml.safe_load(f)
    global base_url
    base_url=config['base']['api_url']
    print('夹具',base_url)
    # os.environ["base_url"] = base_url


# 获取验证码
@pytest.fixture(scope='session', autouse=True)
def captcha():
    req = requests.Session()
    response = req.get('https://test.kindstaryouyi.com/apis/auth/v1/captcha')
    a = response.json()['data']
    image_data = base64.b64decode(a)
    with open('test_data/output.jpg', 'wb') as f:
        f.write(image_data)
    ocr = ddddocr.DdddOcr()
    res = ocr.classification(image_data)
    with open('test_data/config.yaml', 'r', encoding='utf-8') as f:
        data1 = yaml.safe_load(f)
    data1['login_data']['c'] = res
    with open('test_data/config.yaml', 'w', encoding='utf-8') as f:
        yaml.dump(data1, f, default_flow_style=False, allow_unicode=True)

@pytest.fixture(scope='session', autouse=True)
def login():
    # req = RequestUtil()
    while True:
        with open('test_data/config.yaml', 'r', encoding='utf-8') as f:
            data1 = yaml.safe_load(f)
        req = requests.Session()
        response = req.post(
            url='https://test.kindstaryouyi.com/apis/auth/v1/login',
            json=data1["login_data"]
        )
        if response.json()['code'] == 0:
            data1['auth'] = response.json()['data']
            with open('test_data/config.yaml', 'w', encoding='utf-8') as f:
                yaml.dump(data1, f, default_flow_style=False, allow_unicode=True)
            print('登录成功')
            # token = response.json()['data']['t']
            # req.session.headers.update({
            #     "Authorization": f"Bearer {token}",
            #     "Content-Type": "application/json",
            # })
            os.environ["API_TOKEN"] = response.json()['data']['t']  # 存入环境变量
            break
        else:
            continue
    return response.json()['data']['t']


# @pytest.fixture
# def api_client(login):
#     req = RequestUtil()
#     req.session.headers.update({
#         "Authorization": f"Bearer {login}",
#         "Content-Type": "application/json",
#     })
#     print('走了吗')
#     return req

